package com.theanh.RssActivity.util;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.util.Log;

import com.theanh.RssActivity.R;
import com.theanh.RssActivity.Store;
import com.theanh.RssActivity.entity.*;
import com.theanh.RssActivity.parser.RssParser;

public final class RssUtils {
	private static final String TAG = "RssUtils";

	public static Channel getChannel(String url) throws Exception {
		RssParser parser = new RssParser(url);
		try {
			parser.parse();
			return parser.getChannel();
		} catch (ParserConfigurationException e) {
			Log.e(TAG, e.toString());

			CharSequence error = Store.context.getString(R.string.parsing_error);
			throw new Exception(error.toString(), e);
		} catch (SAXException e) {
			Log.e(TAG, e.toString());
			
			CharSequence error = Store.context.getString(R.string.parsing_error);
			throw new Exception(error.toString(), e);
		} catch (IOException e) {
			Log.e(TAG, e.toString());
			
			CharSequence error = Store.context.getString(R.string.connection_error);
			throw new Exception(error.toString(), e);
		}
	}
	
	public static void fillChannel(Channel channel) throws Exception{
		if (channel == null)
			return;
		
		Channel ch = getChannel(channel.getUrl());
		channel.setLogoUrl(ch.getLogoUrl());
		channel.setItems(ch.getItems());
		if (channel.getItems() == null)
			return;
		
		for(Item item : channel.getItems()){
			item.setChannelID(channel.getID());
			
			item.setImageUrl(Utils.paresImageUrlFromXml(item.getDescription()));
			item.setDescription(Utils.removeTagHtml2(item.getDescription()));
			item.setDescription(StringUtils.processEncodedHtmlTag(item.getDescription()));
			item.setDescription(StringUtils.processEncodedHtmlCharacters(item.getDescription()));
		}

	}
}
